// pages/publish-processing/publish-processing.ts
import { createProcessing } from '../../../api/publish.js'
import { getCategoryNames, getProductsByCategory } from '../../../config/product-categories.js'
import { PAGE_PUBLISH_SELECT, PAGE_PRODUCT_DETAIL, goToPage } from '../../../config/pages.js'
import userManager from '../../../utils/userManager.js'

interface SpecItem {
  mm: string;
  m: string;
}

interface AddressItem {
  name: string;
  value: string;
}

interface CategoryItem {
  name: string;
  value: string;
}

interface FormData {
  product_category: string;
  product_name: string;
  product_model: string;
  processing_accuracy: string;
  processing_width: string;
  processing_equipment: string;
  specs: SpecItem[];
  total_amount: string;
  remark: string;
  contact_name: string;
  contact_phone: string;
  contact_email: string;
  province: string;
  city: string;
  district: string;
  province_id: number;
  city_id: number;
  district_id: number;
  detail_address: string;
}

Page({
  data: {
    // 表单数据
    formData: {
      product_category: '',
      product_name: '',
      product_model: '',
      processing_accuracy: '',
      processing_width: '',
      processing_equipment: '',
      specs: [
        { mm: '', m: '' }
      ],
      total_amount: '',
      remark: '',
      contact_name: '',
      contact_phone: '',
      contact_email: '',
      province: '',
      city: '',
      district: '',
      province_id: 0,
      city_id: 0,
      district_id: 0,
      detail_address: ''
    } as FormData,
    
    // 产品类别数据
    categoryList: getCategoryNames(),
    categoryIndex: 0,
    
    // 产品名称数据
    productList: [] as string[],
    productIndex: 0,
    showCategoryPicker: false,
    showProductPicker: false,
    
    
    // 图片上传
    uploadedImages: [] as string[],
    uploadedImageUrls: [] as string[],
    uploadingImages: false,
    
    // 发布成功后的单据ID
    publishedId: 0
  },

  onLoad() {
    console.log('发布加工页面加载完成');
    this.loadUserInfo();
  },

  onShow() {
    console.log('发布加工页面显示');
  },

  // 加载用户信息并填入表单
  async loadUserInfo() {
    try {
      const userInfo = await userManager.getUserInfo() as any;
      if (userInfo) {
        this.setData({
          'formData.contact_name': userInfo.real_name || userInfo.nickname || '',
          'formData.contact_phone': userInfo.phone || ''
        });
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
    }
  },

  // 显示产品类别选择器
  showCategoryPicker() {
    this.setData({
      showCategoryPicker: true
    });
  },

  // 显示产品名称选择器
  showProductPicker() {
    this.setData({
      showProductPicker: true
    });
  },

  // 产品类别选择器变化
  onCategoryPickerChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      categoryIndex: index
    });
  },

  // 产品名称选择器变化
  onProductPickerChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      productIndex: index
    });
  },

  // 隐藏产品类别选择器
  hideCategoryPicker() {
    this.setData({
      showCategoryPicker: false
    });
  },

  // 确认产品类别选择
  confirmCategoryPicker() {
    const index = this.data.categoryIndex || 0;
    const category = this.data.categoryList[index];
    const products = getProductsByCategory(category);
    this.setData({
      'formData.product_category': category,
      'formData.product_name': '', // 清空产品名称
      productList: products,
      productIndex: 0,
      showCategoryPicker: false
    });
  },

  // 隐藏产品名称选择器
  hideProductPicker() {
    this.setData({
      showProductPicker: false
    });
  },

  // 确认产品名称选择
  confirmProductPicker() {
    const index = this.data.productIndex || 0;
    const product = this.data.productList[index];
    this.setData({
      'formData.product_name': product,
      showProductPicker: false
    });
  },

  // 产品型号输入
  onModelInput(e: any) {
    this.setData({
      'formData.product_model': e.detail.value
    });
  },

  // 加工精度输入
  onProcessingAccuracyInput(e: any) {
    this.setData({
      'formData.processing_accuracy': e.detail.value
    });
  },

  // 加工门幅输入
  onProcessingWidthInput(e: any) {
    this.setData({
      'formData.processing_width': e.detail.value
    });
  },

  // 加工设备输入
  onProcessingEquipmentInput(e: any) {
    this.setData({
      'formData.processing_equipment': e.detail.value
    });
  },

  // 备注输入
  onRemarkInput(e: any) {
    this.setData({
      'formData.remark': e.detail.value
    });
  },

  // 联系人输入
  onContactNameInput(e: any) {
    this.setData({
      'formData.contact_name': e.detail.value
    });
  },

  // 联系电话输入
  onContactPhoneInput(e: any) {
    this.setData({
      'formData.contact_phone': e.detail.value
    });
  },

  // 邮箱输入
  onEmailInput(e: any) {
    this.setData({
      'formData.contact_email': e.detail.value
    });
  },

  // 总量输入
  onTotalAmountInput(e: any) {
    this.setData({
      'formData.total_amount': e.detail.value
    });
  },

  // 详细地址输入
  onDetailAddressInput(e: any) {
    this.setData({
      'formData.detail_address': e.detail.value
    });
  },

  // 规格输入
  onSpecInput(e: any) {
    const { index, type } = e.currentTarget.dataset;
    const value = e.detail.value;
    const specs = [...this.data.formData.specs];
    (specs[index] as any)[type] = value;
    this.setData({
      'formData.specs': specs
    });
  },

  // 添加规格项
  addSpecItem() {
    const specs = [...this.data.formData.specs];
    specs.push({ mm: '', m: '' } as SpecItem);
    this.setData({
      'formData.specs': specs
    });
  },

  // 删除规格项
  removeSpecItem(e: any) {
    const index = e.currentTarget.dataset.index;
    const specs = [...this.data.formData.specs];
    specs.splice(index, 1);
    this.setData({
      'formData.specs': specs
    });
  },

  // 图片上传成功回调
  onImageUploadSuccess(e: any) {
    const { allImages, allImageUrls } = e.detail;
    console.log('图片上传成功，完整数据:', allImages);
    console.log('图片URL列表:', allImageUrls);
    
    // 保存完整的图片数据对象
    this.setData({
      uploadedImages: allImages,           // 保存完整的 data 对象，包含 url, name, size 等
      uploadedImageUrls: allImageUrls      // 保存 URL 列表，用于显示和提交
    });
  },

  // 图片删除回调
  onImageRemove(e: any) {
    const { remainingImages, remainingImageUrls } = e.detail;
    console.log('删除图片后剩余数据:', remainingImages);
    
    // 更新图片数据
    this.setData({
      uploadedImages: remainingImages,           // 剩余的完整数据对象
      uploadedImageUrls: remainingImageUrls      // 剩余的 URL 列表
    });
  },

  // 地址选择变化
  onAddressChange(e: any) {
    const { address } = e.detail;
    if (address) {
      this.setData({
        'formData.province': address.province,
        'formData.city': address.city,
        'formData.district': address.district,
        'formData.province_id': address.province_id,
        'formData.city_id': address.city_id,
        'formData.district_id': address.district_id
      });
    }
  },

  // 发布加工
  async publishProcessing() {
    // 表单验证
    if (!this.validateForm()) {
      return;
    }
    
    // 显示加载中
    wx.showLoading({
      title: '发布中...'
    });
    
    try {
      // 准备提交数据
      const submitData: any = {
        ...this.data.formData,
        spec: JSON.stringify(this.data.formData.specs || [])
      };
      
      // 添加产品图片信息（使用完整的图片数据）
      if (this.data.uploadedImages.length > 0) {
        submitData.product_image_atts = JSON.stringify(
          this.data.uploadedImages.map((img: any) => ({
            url: img.url,
            name: img.name || '产品图片',
            size: img.size,
            path: img.path
          }))
        );
      }

      // 调用API创建加工
      const result = await createProcessing(submitData);
      
      if (result.status === 200 || result.code === 200) {
        wx.hideLoading();
        // 保存发布成功的单据ID
        if (result.data && result.data.id) {
          this.setData({
            publishedId: result.data.id
          });
        }
        this.showPublishSuccessModal();
      } else {
        wx.hideLoading();
        wx.showToast({
          title: result.msg || '发布失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('发布加工失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '发布失败，请重试'),
        icon: 'none'
      });
    }
  },

  // 表单验证
  validateForm(): boolean {
    const { formData, uploadedImages } = this.data;
    
    if (!formData.product_category) {
      wx.showToast({
        title: '请选择产品类别',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_name) {
      wx.showToast({
        title: '请选择产品名称',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_model.trim()) {
      wx.showToast({
        title: '请输入产品型号',
        icon: 'none'
      });
      return false;
    }
    
    /*if (!formData.total_amount.trim()) {
      wx.showToast({
        title: '请输入总数量',
        icon: 'none'
      });
      return false;
    }*/
    
    /*if (uploadedImages.length === 0) {
      wx.showToast({
        title: '请至少上传1张产品图片',
        icon: 'none'
      });
      return false;
    }*/
    
    if (!formData.contact_name.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return false;
    }
    
    
    if (!formData.province) {
      wx.showToast({
        title: '请选择联系地址',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.detail_address.trim()) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  },

  // 显示发布成功模态框
  showPublishSuccessModal() {
    wx.showModal({
      title: '发布完成',
      content: '您的加工信息已成功发布，等待客户联系',
      showCancel: true,
      cancelText: '查看详情',
      confirmText: '继续发布',
      success: (res) => {
        if (res.confirm) {
          // 继续发布 - 使用switchTab跳转到发布选择页
          goToPage(PAGE_PUBLISH_SELECT, {}, 'switchTab');
        } else if (res.cancel) {
          // 查看详情 - 跳转到产品详情页，携带ID和类型
          if (this.data.publishedId) {
            goToPage(PAGE_PRODUCT_DETAIL, { id: this.data.publishedId, type: 'processing' }, 'redirectTo');
          } else {
            // 如果没有ID，返回上一页
            wx.navigateBack();
          }
        }
      }
    });
  }
});
